/*
尽可能还原 Promise 中的每一个 API, 并通过注释的方式描述思路和原理.
*/
/*
    原型方法：
        1、resolve
        2、reject
        3、then
        4、finally
        5、catch
    
    静态方法：
        1、resolve
        2、all
        3、race
*/


// 定义状态常量
const PENDING = 'pending'
const FULFILLED = 'fulfilled'
const REJECTED = 'rejected'

class MyPromise {
    constructor (executor) {
        // 错误处理
        try {   
            executor(this.resolve, this.reject)
        } catch (e) {
            this.reject(e)
        }
    }

    status = PENDING // promise 状态

    value = undefined // 成功状态值

    reason = undefined // 失败状态值

    successCallback = []

    failCallback = []

    resolve = val => {
        if(this.status !== PENDING ) return 
        this.status = FULFILLED
        this.value = val

        while (this.successCallback.length) this.successCallback.shift()()
    }   

    reject = reason => {
        if(this.status !== PENDING ) return 
        this.status = REJECTED
        this.reason = reason

        while (this.failCallback.length) this.failCallback.shift()()
    }

    then (successCallback, failCallback) {
        // 处理回调函数
        successCallback = successCallback ? successCallback : value => value
        failCallback = failCallback ? failCallback : reason => { throw reason } // 这里需要用 throw 抛出失败原因
        
        // then 返回的也是一个 promise
        let promise2 = new MyPromise((resolve, reject) => {
            // 成功、失败、等待三种情况
            if (this.status === FULFILLED) {
                // 加上 setTimeout 变成异步代码，resolvePromise 才能获取到执行完成后的 promise2
                // 判断 x 的值是普通值还是 promise 对象
                // 如果是普通值，直接调用 resolve
                // 如果是 promise 对象，查看 promise 对象的返回结果
                // 再根据 promise 对象返回的结果，决定调用 resolve 还是 reject

                setTimeout(() => {
                    try {   
                        let x = successCallback(this.value)
                        resolvePromise(promise2, x, resolve, reject)
                    } catch (e) {
                        reject(e)
                    }
                }, 0)
            } else if (this.status === REJECTED) {
                setTimeout(() => {
                    try {   
                        let x = failCallback(this.reason)
                        resolvePromise(promise2, x, resolve, reject)
                    } catch (e) {
                        reject(e)
                    }
                }, 0)
            } else { // pending 等待情况，将成功和失败回调存储起来
                this.successCallback.push(() => {
                    setTimeout(() => {
                        try {
                            let x = successCallback(this.value)
                            resolvePromise(promise2, x, resolve, reject)
                        } catch (e) {
                            reject(e)
                        }
                    }, 0)
                })
                this.failCallback.push(() => {
                    setTimeout(() => {
                        try {
                            let x = failCallback(this.reason)
                            resolvePromise(promise2, x, resolve, reject)
                        } catch (e) {
                            reject(e)
                        }
                    }, 0)
                })
            }
        })

        return promise2
    }

    // 1、promise 对象的状态不管是成功还是失败，finally 方法都会执行一次
    // 2、finally 方法的后面，可以链式调用 then 方法，来拿到当前 promise 对象返回的结果
    finally (callback) {
        return this.then(value => {
            // 返回一个 promise，并将当前值传给下一个 then
            return MyPromise.resolve(callback).then(() => value)
        }, reason => {
            return MyPromise.resolve(callback).then(() => { throw reason })
        })
    }

    // 只处理状态为失败的情况
    catch (callback) {
        return this.then(undefined, callback)
    }

    // resolve 方法返回的也是一个 promise
    static resolve (value) {
        if (value instanceof MyPromise) {
            return value
        } else {
            return new MyPromise((resolve, reject) => {
                resolve(value)
            })
        }
    }

    // 只有全部是成功状态，才返回成功，否则返回失败
    static all (array) {
        let result = []
        let index = 0
        
        // all 返回的也是一个 promsie
        return new MyPromise((resolve, reject) => {
            function addData (key, value) {
                result[key] = value
                index++
                if (index === array.length) {
                    resolve(result)
                }
            }
            for (let i = 0; i < array.length; i++) {
                let current = array[i]
                if (current instanceof MyPromise) {
                    current.then(value => addData(i, value), reason => reject(reason))
                } else {
                    addData(i, current)
                }
            }
        })
    }

    // 1、返回一个 promise 
    // 2、返回第一个先执行完成（成功或者失败）的值
    static race (array) {
        return new MyPromise((resolve, reject) => {
            for (let i = 0; i < array.length; i++) {
                let current = array[i]
                if (current instanceof MyPromise) {
                    current.then(value => resolve(value), reason => reject(reason))
                } else {
                    resolve(current)
                }
            }
        })
    }
}

function resolvePromise (promise2, x, resolve, reject) {
    if (promise2 === x) { // 判断是否是自身的情况
        return reject(new TypeError('Chaining cycle detected for promise #<Promise>'))
    }
    if (x instanceof MyPromise) {
        x.then(resolve, reject)
    } else {
        resolve(x)
    }
}


// 测试
let p1 = new MyPromise((resolve, reject) => {
    setTimeout(() => {
        resolve('p1 100')
    }, 2000)
    // reject('失败。。。。')
})
let p2 = new MyPromise((resolve, reject) => {
    resolve('p2 100')
    // reject('失败。。。。')
})

let p3 = MyPromise.resolve(1)

MyPromise.all([p1, p2, p3, 3, 4])
.then()
.then(value => console.log('成功：', value))
.catch(err => console.log('失败：', err))